package com.element.oauth2.server.global.converter;

import com.common.core.exception.code.SecurityErrorCode;
import com.element.oauth2.exception.ClientAuthenticationException;
import com.element.oauth2.server.global.token.ParamAuthenticationToken;
import io.netty.util.internal.StringUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationConverter;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class ParamAuthenticationConverter implements AuthenticationConverter {

    private final AuthorizationGrantType authorizationGrantType;

    public ParamAuthenticationConverter(AuthorizationGrantType authorizationGrantType) {
        this.authorizationGrantType = authorizationGrantType;
    }

    @Override
    public Authentication convert(HttpServletRequest request) {
        String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
        if (StringUtil.isNullOrEmpty(grantType)) {
            throw ClientAuthenticationException.ERROR(SecurityErrorCode.A_UNSUPPORTED_GRANT_TYPE);
        }
        if (!authorizationGrantType.getValue().equals(grantType)) {
            return null;
        }
        // 获取请求中的参数
        Map<String, String> parameters = getParameters(request);
        return new ParamAuthenticationToken(parameters, authorizationGrantType);
    }

    private Map<String, String> getParameters(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> parameters = new HashMap<>(parameterMap.size());
        parameterMap.forEach((key, values) -> {
            for (String value : values) {
                parameters.put(key, value);
            }
        });
        return parameters;
    }
}
